package org.mcjug.oauth;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import oauth.signpost.OAuth;

import org.mcjug.oauth.xauth.XoauthAuthenticator;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;

import com.sun.mail.smtp.SMTPTransport;

public class GmailService extends Service {

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Email email = intent
				.getParcelableExtra(Constants.GMAIL_SERVICE_EMAIL_PARCELABLE_NAME);
		sendEmail(email);

		return START_NOT_STICKY;
	}

	private void sendEmail(Email email) {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		String oauthToken = sp.getString(OAuth.OAUTH_TOKEN, null);
		String oauthTokenSecret = sp.getString(OAuth.OAUTH_TOKEN_SECRET, null);
		if (oauthToken == null || oauthTokenSecret == null) {
			Intent intent = new Intent(
					Constants.NO_TOKENS_FOR_EMAIL_INTENT_ACTION);
			sendBroadcast(intent);
			return;
		}

		try {
			SMTPTransport smtpTransport = XoauthAuthenticator.connectToSmtp(
					Constants.SMTP_ADDRESS, Constants.SMTP_PORT,
					email.getSender(), oauthToken, oauthTokenSecret,
					XoauthAuthenticator.getAnonymousConsumer(), true);
			Properties props = System.getProperties();
			props.put(Constants.SMTP_HOST_PROPERTY_KEY,
					Constants.SMTP_HOST_PROPERTY_VALUE);
			props.put(Constants.SMTP_AUTH_PROPERTY_KEY,
					Constants.SMTP_AUTH_PROPERTY_VALUE);
			Session session = Session.getInstance(props, null);
			Message msg = new MimeMessage(session);
			msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(email.getRecipient(), false));
			msg.setFrom(new InternetAddress(email.getSender()));
			msg.setSubject(email.getSubject());
			msg.setText(email.getBody());
			msg.setHeader(Constants.SMTP_MSG_HEADER_KEY,
					Constants.SMTP_MSG_HEADER_VALUE);
			msg.setSentDate(new Date(System.currentTimeMillis()));
			smtpTransport.sendMessage(msg, msg.getAllRecipients());
		} catch (Exception e) {
			e.printStackTrace();
			Intent intent = new Intent(Constants.EMAIL_FAILURE_INTENT_ACTION);
			sendBroadcast(intent);
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
